<?php

namespace App\Http\Controllers\Admin\User;

use App\Http\Requests\PasswordRequest;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserName extends Controller
{
    /**
     * 这是用户类的资源控制器
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //获得用户数据，并且以每5条分页
        $users = User::paginate(10);
        //加载用户管理列表模板
        return view('admin.admin_user.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::find($id);
        //dd($user);
        $this->authorize('update',$user);
        //向视图中传递user变量的值
        return view('admin.admin_user.edit',compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id,PasswordRequest $passwordRequest)
    {
        //找到当前$id对应的用户数据
        $user = User::find($id);
        //接收post数据
        $post = $request->all();

        $user->username = $post['username'];
        //判断密码是否填写，如果填写了密码，就将用户的密码修改
        if ($post['password']){
            $user->password = bcrypt($post['password']);
        }
        //将用户数据保存
        $user->save();
        //设置闪存信息，并返回编辑
        session()->flash('success','资料修改成功');
        return redirect()->route('user.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //通过对应ID找到删除的用户数据
        $user = User::find($id);
        //判断是否有权限删除
        $this->authorize('delete',$user);
        //1.对应删除1个
        //$user->delete();
        //2.直接使用模型调用destroy方法，可用于批量删除
        User::destroy($id);
        //设置闪存信息，并跳转
        session()->flash('success','用户数据删除成功！');
        //跳转到编辑页面
        return redirect()->route('user.index');
    }
}
